<template>
  <div class="payment-statistics">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>支付统计</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportToCsv"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" size="small">
          <el-form-item label="渠道">
            <el-select 
              v-model="filterForm.channel" 
              placeholder="请选择渠道" 
              style="width: 150px;"
              clearable>
              <el-option
                v-for="item in channelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 240px;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        :data="paymentData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
      >
        <el-table-column prop="create_time" label="日期" width="120"></el-table-column>
        <el-table-column prop="channel" label="渠道" width="80"></el-table-column>
        <el-table-column prop="register" label="当日注册人数" width="120"></el-table-column>
        <el-table-column prop="active" label="当日活跃人数" width="120"></el-table-column>
        <el-table-column prop="amount" label="充值笔数" width="100"></el-table-column>
        <el-table-column prop="player_amount" label="充值人数" width="100"></el-table-column>
        <el-table-column prop="rtp" label="充值金额rp" width="120"></el-table-column>
        <el-table-column prop="rmb" label="折合￥" width="120"></el-table-column>
        <el-table-column prop="dollar" label="折合$" width="120"></el-table-column>
        <el-table-column prop="coin" label="充值产生金币" width="120"></el-table-column>
        <el-table-column prop="register_amount" label="新注册充值人数" width="140"></el-table-column>
        <el-table-column prop="register_coin" label="新注册金额" width="140"></el-table-column>
        <el-table-column prop="first_amount" label="历史首充人数" width="120"></el-table-column>
        <el-table-column prop="first_coin" label="历史首充金额" width="120"></el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { payStatistic } from '@/api/user'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'PaymentStatistics',
  mixins: [channelMixin],
  data() {
    return {
      paymentData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      exportLoading: false,
      filterForm: {
        channel: null,
        dateRange: null
      }
    }
  },
  async mounted() {
    this.fetchData()
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          channel: this.filterForm.channel ? parseInt(this.filterForm.channel) : 0,
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : ''
        }
        
        const response = await payStatistic(params)
        
        if (response && response.code === 0) {
          // 处理可能的数据结构差异
          let records = []
          if (response.data && response.data.pays && Array.isArray(response.data.pays)) {
            records = response.data.pays
          } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
          } else if (Array.isArray(response.data)) {
            records = response.data
          } else if (response.data && typeof response.data === 'object') {
            for (let key in response.data) {
              if (Array.isArray(response.data[key])) {
                records = response.data[key]
                break
              }
            }
          }
          
          this.paymentData = records
          
          // 处理分页信息
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else {
            this.total = records.length
          }
        } else {
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取支付统计数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    async exportToCsv() {
      this.exportLoading = true
      
      try {
        // 获取所有数据用于导出
        const params = {
          page: 1,
          page_size: 10000,
          channel: this.filterForm.channel ? parseInt(this.filterForm.channel) : 0,
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : ''
        }
        
        const response = await payStatistic(params)
        let allData = []
        
        if (response && response.code === 0) {
          if (response.data && response.data.pays && Array.isArray(response.data.pays)) {
            allData = response.data.pays
          } else if (response.data && Array.isArray(response.data)) {
            allData = response.data
          } else if (response.data && typeof response.data === 'object') {
            for (let key in response.data) {
              if (Array.isArray(response.data[key])) {
                allData = response.data[key]
                break
              }
            }
          }
        }
        
        // 构建CSV内容
        let csvContent = '日期,渠道,当日注册人数,当日活跃人数,充值笔数,充值人数,充值金额rp,折合￥,折合$,充值产生金币,新注册充值人数,新注册金额,历史首充人数,历史首充金额\n'
        
        allData.forEach(row => {
          csvContent += `${row.time},${row.channel},${row.register},${row.active},${row.amount},${row.player_amount},${row.rtp},${row.rmb},${row.dollar},${row.coin},${row.register_amount},${row.register_coin},${row.first_amount},${row.first_coin}\n`
        })
        
        // 创建Blob对象并下载
        const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a')
        const url = URL.createObjectURL(blob)
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        link.setAttribute('href', url)
        link.setAttribute('download', `支付统计_${dateStr}.csv`)
        link.style.visibility = 'hidden'
        
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.exportLoading = false
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetFilter() {
      this.filterForm = {
        channel: null,
        dateRange: null
      }
      this.currentPage = 1
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.payment-statistics {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.filter-section {
  margin-bottom: 20px;
}
</style> 